
//
//  UITextView + Extension.swift
//  EmojiKeyboardTest
//
//  Created by dqw on 15/8/6.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit


extension UITextView {
    
    func insertEmoticon(emoticon: DDEmoticon) {
        
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            return
        }
        
        if emoticon.chs != nil {
            let h = font!.lineHeight
            let attachment = DDAttachment()
            attachment.chs = emoticon.chs
            attachment.image = UIImage(contentsOfFile: emoticon.imagePath!)
            attachment.bounds = CGRect(x: 0, y: -4, width: h, height: h)
            let imageString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            imageString.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
            let textString = NSMutableAttributedString(attributedString: attributedText)
            // FIXME: 注意连个不同的range。
            textString.replaceCharactersInRange(selectedRange, withAttributedString: imageString)
            let range = selectedRange
            attributedText = textString
            selectedRange = NSRange(location: range.location + 1, length: 0)
        }
    }
    
     func translateCompoundedTextIntoString() -> String? {
        
        var strM = String()
        let compoundedText = attributedText
        compoundedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? DDAttachment {
                
                strM += attachment.chs!
            }else {
                let str = (compoundedText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }
}
